package cn.emergentdesign.demo.bowling;

import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.IntStream;

public class BowlingGame {
    private int frameIndex;
    private List<Frame> frames;
    public BowlingGame() {
        frames = IntStream.range(0, 10)
                .mapToObj(i -> new Frame())
                .collect(Collectors.toList());
        frameIndex = 0;
    }

    /**
     * 掷球
     * @param pins 击倒的瓶数
     */
    public void roll(int pins) {
        if (isOver()) {
            throw new GameOverException();
        }
        addBonus(pins);

        // 如果10轮比赛已经结束，奖励分记完后，就不再计分
        if (frameIndex>=10){
            return;
        }

        // 当前轮比赛
        Frame currentFrame = frames.get(frameIndex);
        currentFrame.roll(pins);
        if (currentFrame.isFinished()) {
            frameIndex++;
        }
    }

    private void addBonus(int pins) {
        frames.forEach(frame -> frame.addBonus(pins));
    }

    /**
     * 计算当前总分
     * @return
     */
    public int score() {
        int score = 0;
        for (Frame frame : frames) {
            score += frame.getScore();
        }
        return score;
    }

    /**
     * 判断游戏是否结束
     * @return
     */
    public boolean isOver() {
        return frameIndex == 10 && allBonusUsed();
    }

    private boolean allBonusUsed() {
        return frames.stream().allMatch(Frame::bonusUsed);
    }
}
